<?php

namespace app\ports\controller;

use think\Db;
use think\Log;

/**
 * 运营资金扣款
 * Class
 * @package
 */
class Works
{
	use \app\common\traits\ToolTrait;

	private $table = "fd_works_cap";

	public function loading()
	{
		try {
			$where = "is_repay in (2,3) and status = 1";
			$ret = Db::table($this->table)->where($where)->column("id");
			if ($ret) {
				for ($i = 0; $i < count($ret); $i++) {
					$this->handle($ret[$i]);
				}
			}
		} catch (\Exception $e) {
			Log::write($e->getMessage());
		}
	}

	/**
	 * 处理
	 */
	public function handle($list_id)
	{
		if ($list_id) {
			// 获取详情
			$find = Db::table($this->table)
				->field("*,case repay_typs when 1 then '运营资金' when 2 then '机具'  end rtNick")
				->where("id", $list_id)->find();
			if ($find) {
				// 获取余额
				$balance = \app\common\controller\Balance::instance()->get($find["user_id"]);
				// $balance = 42531.65;
				if ($balance > 0) {
					$isRepay = 2;
					$dedcAmt = $balance;
					// 扣款金额 - 已扣款 = 剩余未扣款
					$rem = bcsub((string)$find["money"], (string)$find["repayMoney"], 2);
					if ($balance >= $rem) {
						$isRepay = 1;
						$dedcAmt = $rem;
					}
					$update = [
						"is_repay"	 => $isRepay,
						"repayMoney" => Db::raw("repayMoney" . " + " . $dedcAmt),
					];
					if ($isRepay == 1) $update["repay_time"] = time();
					$ret = Db::table($this->table)->where("id", $find["id"])->update($update);
					if ($ret) {
						$typs = 0;
						switch ($find["repay_typs"]) {
							case 1:
								$typs = 12;
								break;
							case 2:
								$typs = 13;
								break;
						}
						$subOption = [
							"uid"        => $find["user_id"],     // 支出 代理ID
							"typs"       => $typs,                 // 变更类型 12 = 运营资金 13 = 机具
							"isChg"      => 2,                 // 2 支出
							"remark"     => $find['rtNick'] . "扣款",    // 备注  => 没有备注传空字符串
							"chgAmt"     => $dedcAmt,    // 变更金额
							"ids"        => 1,        // 操作订单主ID 
						];
						\app\common\controller\Balance::instance()->sub_and_logs($subOption);
					}
				}
			}
		}
	}
}
